<template>
  <div class="list-page">
    <EmergencyVerticalTabNav />
    <div class="content-container">
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="display: flex;justify-content: space-between;width: 100%;">
            <div>
              <el-form-item label="预案名称" prop="planName">
                <el-input v-model="queryParams.planName" placeholder="请输入预案名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="预案类型" prop="planType">
                <el-select v-model="queryParams.planType" placeholder="请选择预案类型" clearable @change="handleQuery">
                  <el-option :value="1" label="总体预案" />
                  <el-option :value="2" label="专项预案" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              </el-form-item>
            </div>
            <div>
              <el-button icon="RefreshRight" @click="resetQuery">刷新</el-button>
              <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
            </div>
          </el-form>
        </el-card>
      </div>

      <!-- 列表区域 -->
      <el-card shadow="hover" class="w-full">
        <el-table
          v-loading="loading"
          :data="tableData"
          @selection-change="handleSelectionChange"
          border
          style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="planName" label="预案名称" min-width="120" />
          <el-table-column prop="planType" label="预案类型" width="120" align="center">
            <template #default="{ row }">
              {{ row.planType === 1 ? '总体预案' : '专项预案' }}
            </template>
          </el-table-column>
          <el-table-column prop="eventCategory" label="适用事件类型" width="150" align="center">
            <template #default="{ row }">
              {{ getEventCategoryName(row.eventCategory) }}
            </template>
          </el-table-column>
          <el-table-column prop="eventLevel" label="适用事件等级" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="getEventLevelTag(row.eventLevel)" :class="['status-tag', `level-${row.eventLevel}`]">
                {{ getEventLevelName(row.eventLevel) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="publishUnit" label="发布单位" width="150" />
          <el-table-column prop="publishDate" label="发布日期" width="120">
            <template #default="{ row }">
              {{ row.publishDate ? formatDate(row.publishDate) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="effectiveDate" label="生效时间" width="120">
            <template #default="{ row }">
              {{ row.effectiveDate ? formatDate(row.effectiveDate) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="planStatus" label="预案状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getPlanStatusTag(row.planStatus)" :class="['status-tag', `status-${row.planStatus}`]">
                {{ getPlanStatusName(row.planStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="attachmentPath" label="附件" width="100" align="center">
            <template #default="{ row }">
              <el-link 
                v-if="row.attachmentPath" 
                type="primary" 
                :underline="false"
                @click.prevent="handleViewAttachment(row)"
              >
                <el-icon><Document /></el-icon> 查看附件
              </el-link>
              <el-button
                v-else
                link
                type="primary"
                @click="handleUploadAttachment(row)"
              >
                <el-icon><Upload /></el-icon> 上传
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            background
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="60%"
        center
        destroy-on-close
        class="custom-dialog"
      >
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">{{ dialogTitle }}</span>
          </div>
        </template>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="预案名称" prop="planName">
            <el-input v-model="form.planName" placeholder="请输入预案名称" />
          </el-form-item>
          <el-form-item label="预案类型" prop="planType">
            <el-radio-group v-model="form.planType">
              <el-radio :label="1">总体预案</el-radio>
              <el-radio :label="2">专项预案</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="适用事件类型" prop="eventCategory">
            <el-select v-model="form.eventCategory" placeholder="请选择适用事件类型" class="w-full">
              <el-option :value="1" label="自然灾害" />
              <el-option :value="2" label="事故灾难" />
              <el-option :value="3" label="公共卫生事件" />
              <el-option :value="4" label="社会安全事件" />
            </el-select>
          </el-form-item>
          <el-form-item label="适用事件等级" prop="eventLevel">
            <el-select v-model="form.eventLevel" placeholder="请选择适用事件等级" class="w-full">
              <el-option :value="1" label="Ⅰ级" />
              <el-option :value="2" label="Ⅱ级" />
              <el-option :value="3" label="Ⅲ级" />
              <el-option :value="4" label="Ⅳ级" />
              <el-option :value="5" label="全部" />
            </el-select>
          </el-form-item>
          <el-form-item label="通知人员" prop="notifyPersonnel" required>
            <el-tree
              ref="deptTreeRef"
              :data="deptOptions"
              :props="{ 
                value: 'deptId',
                label: 'deptName',
                children: 'children'
              }"
              show-checkbox
              node-key="deptId"
              default-expand-all
              :render-content="renderContent"
              @check="handleCheck"
              @check-change="handleCheckChange"
              class="w-full"
            />
            <div v-if="deptOptions.length === 0" class="text-red-500 text-sm mt-1">
              暂无部门数据可选
            </div>
          </el-form-item>
          <el-form-item label="发布单位" prop="publishUnit">
            <el-input v-model="form.publishUnit" placeholder="请输入发布单位" />
          </el-form-item>
          <el-form-item label="发布日期" prop="publishDate">
            <el-date-picker
              v-model="form.publishDate"
              type="date"
              placeholder="选择发布日期"
              value-format="YYYY-MM-DD"
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="生效时间" prop="effectiveDate">
            <el-date-picker
              v-model="form.effectiveDate"
              type="date"
              placeholder="选择生效时间"
              value-format="YYYY-MM-DD"
              class="w-full"
            />
          </el-form-item>
          <el-form-item label="预案状态" prop="planStatus">
            <el-radio-group v-model="form.planStatus">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">停用</el-radio>
              <el-radio :label="3">修订中</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 附件弹窗 -->
      <el-dialog
        v-model="attachmentDialogVisible"
        title="附件列表"
        width="600px"
        center
        destroy-on-close
        class="custom-dialog">
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">附件列表</span>
          </div>
        </template>
        <div class="attachment-container">
          <el-table :data="attachmentList" style="width: 100%">
            <el-table-column prop="fileName" label="文件名称" />
            <el-table-column label="操作" width="200" align="center">
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="handleDownload(row)"
                >
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  link
                  @click="handleDeleteAttachment(row)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <template #footer>
          <el-button @click="attachmentDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>

      <!-- 文件上传对话框 -->
      <el-dialog
        v-model="uploadDialogVisible"
        title="上传附件"
        width="500px"
        center
        destroy-on-close
        class="custom-dialog"
      >
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">上传附件</span>
          </div>
        </template>
        <div class="upload-container">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="10"
            :on-exceed="handleExceed"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeUpload"
            multiple
            action="#"
            :file-list="uploadFiles"
          >
            <template #trigger>
              <el-button type="primary">
                <el-icon><Plus /></el-icon> 选择文件
              </el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持任意格式文件，单个文件不超过5MB
              </div>
            </template>
          </el-upload>

          <div v-if="uploadProgress.total > 0" class="upload-progress">
            <div class="progress-text">
              正在上传: {{ uploadProgress.current }}/{{ uploadProgress.total }}
            </div>
            <el-progress 
              :percentage="(uploadProgress.current / uploadProgress.total) * 100"
              :format="progressFormat"
              :status="uploadProgress.status"
            />
          </div>
        </div>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="uploadDialogVisible = false">取消</el-button>
            <el-button 
              type="primary" 
              @click="submitUpload"
              :loading="uploading"
              :disabled="!uploadFiles.length"
            >
              开始上传
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, getCurrentInstance, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getEmergencyPlanList,
  getEmergencyPlanById,
  addEmergencyPlan,
  updateEmergencyPlan,
  deleteEmergencyPlan,
  uploadEmergencyPlanAttachment,
  deleteEmergencyPlanAttachment
} from "@/api/bridge/command/emergency";
import {
  getPlanNoticeRecord,
  addPlanNoticeRecord,
  updatePlanNoticeRecord, 
  deletePlanNoticeRecord,
  getPlanNoticeRecordInfo
} from "@/api/bridge/command/dept";
import { listDept } from "@/api/system/dept";
import { getUserInfoList } from "@/api/bridge/user/user";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { Plus, Reading, Document, Search, Upload, Download, Delete } from '@element-plus/icons-vue';

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);

// 路由
const router = useRouter();
const attachmentDialogVisible = ref(false);
const attachmentList = ref([]);

// 跳转到应急知识条目页面
const goToKnowledge = () => {
  router.push('/coordination-command/emergency-knowledge');
};

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const fileList = ref([]);
const deptOptions = ref([]);

// 树形选择器引用
const deptTreeRef = ref();

// 自定义节点渲染
const renderContent = (h, { node, data }) => {
  return h('div', { class: 'custom-tree-node' }, [
    h('span', { class: 'node-label' }, [
      h('span', null, node.label),
      // 显示用户数量
      h('span', { class: 'user-count' }, ` (${data.users?.length || 0}人)`)
    ]),
    // 用户列表
    h('div', { class: 'user-list' }, 
      data.users?.map(user => 
        h('div', { 
          class: 'user-item',
          key: user.userId,
          onClick: (e) => {
            e.stopPropagation();
            handleUserSelect(user, node);
          }
        }, [
          h('el-checkbox', {
            modelValue: isUserSelected(user),
            'onUpdate:modelValue': (val) => handleUserCheck(user, val),
            onClick: (e) => e.stopPropagation()
          }, user.nickName || user.userName)
        ])
      )
    )
  ]);
};

// 处理部门选择
const handleCheck = (data, { checkedKeys, checkedNodes, halfCheckedKeys, halfCheckedNodes }) => {
  console.log('部门选择变化:', {
    data,
    checkedKeys,
    checkedNodes,
    halfCheckedKeys,
    halfCheckedNodes
  });
  
  // 更新选中的用户列表
  updateSelectedUsers();
};

// 处理部门选择状态变化
const handleCheckChange = (data, checked, indeterminate) => {
  console.log('部门选择状态变化:', {
    data,
    checked,
    indeterminate
  });
  
  // 更新父节点的选中状态
  updateParentNodeStatus(data);
};

// 处理用户选择
const handleUserSelect = (user, node) => {
  // 阻止事件冒泡，避免触发部门选择
  event.stopPropagation();
};

// 处理用户复选框变化
const handleUserCheck = (user, checked) => {
  const userKey = `${user.deptId}-${user.userId}`;
  if (checked) {
    if (!form.value.notifyPersonnel.includes(userKey)) {
      form.value.notifyPersonnel.push(userKey);
    }
  } else {
    form.value.notifyPersonnel = form.value.notifyPersonnel.filter(key => key !== userKey);
  }
  
  // 更新部门节点的选中状态
  updateDeptNodeStatus(user.deptId);
};

// 检查用户是否被选中
const isUserSelected = (user) => {
  const userKey = `${user.deptId}-${user.userId}`;
  return form.value.notifyPersonnel.includes(userKey);
};

// 更新选中的用户列表
const updateSelectedUsers = () => {
  const tree = deptTreeRef.value;
  if (!tree) return;
  
  const checkedNodes = tree.getCheckedNodes();
  const halfCheckedNodes = tree.getHalfCheckedNodes();
  
  // 收集所有选中的用户
  const selectedUsers = [];
  
  // 处理完全选中的节点
  checkedNodes.forEach(node => {
    if (node.users) {
      node.users.forEach(user => {
        const userKey = `${user.deptId}-${user.userId}`;
        if (!selectedUsers.includes(userKey)) {
          selectedUsers.push(userKey);
        }
      });
    }
  });
  
  // 处理半选中的节点
  halfCheckedNodes.forEach(node => {
    if (node.users) {
      node.users.forEach(user => {
        const userKey = `${user.deptId}-${user.userId}`;
        if (isUserSelected(user) && !selectedUsers.includes(userKey)) {
          selectedUsers.push(userKey);
        }
      });
    }
  });
  
  form.value.notifyPersonnel = selectedUsers;
};

// 更新部门节点的选中状态
const updateDeptNodeStatus = (deptId) => {
  const tree = deptTreeRef.value;
  if (!tree) return;
  
  const node = tree.getNode(deptId);
  if (!node) return;
  
  // 获取该部门下所有选中的用户
  const selectedUsers = form.value.notifyPersonnel.filter(key => 
    key.startsWith(`${deptId}-`)
  );
  
  // 获取该部门下所有用户
  const allUsers = node.data.users || [];
  
  // 更新节点状态
  if (selectedUsers.length === allUsers.length) {
    node.checked = true;
    node.indeterminate = false;
  } else if (selectedUsers.length > 0) {
    node.checked = false;
    node.indeterminate = true;
  } else {
    node.checked = false;
    node.indeterminate = false;
  }
  
  // 递归更新父节点状态
  updateParentNodeStatus(node.data);
};

// 更新父节点状态
const updateParentNodeStatus = (data) => {
  const tree = deptTreeRef.value;
  if (!tree) return;
  
  const node = tree.getNode(data.deptId);
  if (!node || !node.parent) return;
  
  const parentNode = node.parent;
  const siblings = parentNode.childNodes;
  
  // 检查所有兄弟节点的状态
  const allChecked = siblings.every(sibling => sibling.checked);
  const someChecked = siblings.some(sibling => sibling.checked || sibling.indeterminate);
  
  // 更新父节点状态
  parentNode.checked = allChecked;
  parentNode.indeterminate = !allChecked && someChecked;
  
  // 递归更新上层父节点
  updateParentNodeStatus(parentNode.data);
};

// 添加样式
const style = document.createElement('style');
style.textContent = `
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

.node-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-count {
  color: #909399;
  font-size: 12px;
}

.user-list {
  margin-left: 24px;
  padding: 4px 0;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 2px 0;
  cursor: pointer;
}

.user-item:hover {
  background-color: var(--el-fill-color-light);
}
`;
document.head.appendChild(style);

// 修改表单初始化数据，增加通知人员字段
const form = ref({
  id: "",
  planName: "",
  planType: 1, // 默认总体预案
  eventCategory: 1, // 默认自然灾害
  eventLevel: 5, // 默认全部
  publishUnit: "",
  publishDate: dayjs().format("YYYY-MM-DD"), // 默认当前日期
  effectiveDate: dayjs().format("YYYY-MM-DD"), // 默认当前日期
  planStatus: 1, // 默认启用
  attachmentPath: "",
  notifyPersonnel: [], // 通知人员
  noticeRecords: [] // 用于存储提交到后端的通知记录
});

// 表单校验规则
const rules = {
  planName: [{ required: true, message: "请输入预案名称", trigger: "blur" }],
  planType: [{ required: true, message: "请选择预案类型", trigger: "change" }],
  eventCategory: [{ required: true, message: "请选择适用事件类型", trigger: "change" }],
  eventLevel: [{ required: true, message: "请选择适用事件等级", trigger: "change" }],
  publishUnit: [{ required: true, message: "请输入发布单位", trigger: "blur" }],
  publishDate: [{ required: true, message: "请选择发布日期", trigger: "change" }],
  effectiveDate: [{ required: true, message: "请选择生效时间", trigger: "change" }],
  planStatus: [{ required: true, message: "请选择预案状态", trigger: "change" }],
  notifyPersonnel: [{ required: true, message: "请至少选择一个通知对象", trigger: "change" }]
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD');
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value,
    };
    const res = await getEmergencyPlanList(params);
    if (res.code === 200) {
      tableData.value = res.rows;
      total.value = res.total;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleQuery = () => {
  currentPage.value = 1;
  getList();
};

const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    planName: null,
    planType: null
});

// 获取部门树状数据
const getDeptTreeData = async () => {
  try {
    // 获取所有部门数据
    const deptRes = await listDept({
      pageNum: 1,
      pageSize: 10000
    });
    
    // 获取所有用户数据
    const userRes = await getUserInfoList({
      pageNum: 1,
      pageSize: 10000
    });
    
    if (deptRes.code === 200 && deptRes.data && deptRes.data.length > 0) {
      console.log('获取到的部门原始数据:', deptRes.data);
      console.log('获取到的用户数据:', userRes.rows);
      
      // 构建用户映射表，按部门ID分组
      const userMap = {};
      if (userRes.code === 200 && userRes.rows) {
        userRes.rows.forEach(user => {
          const deptId = String(user.deptId);
          if (!userMap[deptId]) {
            userMap[deptId] = [];
          }
          userMap[deptId].push({
            userId: user.userId,
            userName: user.userName,
            nickName: user.nickName,
            deptId: deptId,
            deptName: user.deptName
          });
        });
      }
      
      // 手动构建树形结构，确保类型匹配
      const buildDeptTree = (data) => {
        // 确保所有ID都转为字符串类型，以便统一比较
        const normalize = data.map(item => ({
          ...item,
          deptId: String(item.deptId),
          parentId: String(item.parentId),
          users: userMap[String(item.deptId)] || [] // 添加用户数据
        }));
        
        // 构建映射表以提高查找效率
        const map = {};
        normalize.forEach(item => {
          map[item.deptId] = { ...item, children: [] };
        });
        
        // 构建树结构
        const tree = [];
        normalize.forEach(item => {
          const parentId = item.parentId;
          const id = item.deptId;
          
          if (map[parentId]) {
            // 将当前节点添加到父节点的children中
            map[parentId].children.push(map[id]);
          } else {
            // 没有父节点或父节点ID为0，作为根节点
            if (parentId === '0') {
              tree.push(map[id]);
            }
          }
        });
        
        return tree;
      };
      
      // 使用手动构建的方法
      const treeData = buildDeptTree(deptRes.data);
      console.log('构建的树形数据:', treeData);
      
      // 如果手动构建的树为空但原始数据不为空，则尝试使用proxy.handleTree
      if (treeData.length === 0 && deptRes.data.length > 0) {
        const { proxy } = getCurrentInstance();
        if (proxy?.handleTree) {
          deptOptions.value = proxy.handleTree(deptRes.data, 'deptId', 'parentId');
          console.log('使用proxy.handleTree构建的树形数据:', deptOptions.value);
        } else {
          // 如果都失败，至少显示平铺的数据
          deptOptions.value = deptRes.data.map(item => ({
            ...item,
            deptId: String(item.deptId),
            label: item.deptName,
            value: String(item.deptId),
            children: [],
            users: userMap[String(item.deptId)] || []
          }));
        }
      } else {
        deptOptions.value = treeData;
      }
    } else {
      console.warn('部门数据获取成功，但数据为空');
      deptOptions.value = [];
    }
  } catch (error) {
    console.error("获取部门数据失败:", error);
    deptOptions.value = [];
  }
};

// 获取预案的通知记录
const getPlanNoticeRecords = async (planId) => {
  try {
    console.log('获取预案通知记录，预案ID:', planId);
    const res = await getPlanNoticeRecord({ planId });
    if (res.code === 200 && res.rows) {
      console.log('获取到的预案通知记录:', res.rows);
      
      // 将通知记录转换为前端需要的格式
      const selectedPersonnel = res.rows.map(record => {
        if (record.personnelId) {
          // 如果有用户ID，使用 deptId-userId 格式
          return `${record.departmentId}-${record.personnelId}`;
        } else {
          // 如果只有部门ID，只返回部门ID
          return String(record.departmentId);
        }
      }).filter(Boolean);
      
      console.log('转换后的选中列表:', selectedPersonnel);
      
      // 更新表单中的选中人员
      form.value.notifyPersonnel = selectedPersonnel;
      
      // 保存原始通知记录数据，用于后续提交
      form.value.noticeRecords = res.rows;

      // 在树形控件中设置选中状态
      nextTick(async () => {
        if (deptTreeRef.value) {
          // 先重置所有选中状态
          deptTreeRef.value.setCheckedKeys([]);
          
          // 处理部门的选中状态
          const deptIds = new Set(res.rows
            .map(record => String(record.departmentId))
            .filter(Boolean));
          
          // 设置部门的选中状态
          deptIds.forEach(deptId => {
            const node = deptTreeRef.value.getNode(deptId);
            if (node) {
              deptTreeRef.value.setChecked(node.key, true, false);
            }
          });

          // 处理用户的选中状态
          selectedPersonnel.forEach(key => {
            if (key.includes('-')) {
              const [deptId] = key.split('-');
              updateDeptNodeStatus(deptId);
            }
          });
        }
      });
    } else {
      console.warn('获取预案通知记录失败:', res.msg);
      form.value.notifyPersonnel = [];
      form.value.noticeRecords = [];
    }
  } catch (error) {
    console.error("获取预案通知记录失败:", error);
    form.value.notifyPersonnel = [];
    form.value.noticeRecords = [];
  }
};

// 处理新增
const handleAdd = async () => {
  dialogTitle.value = "新增应急预案";
  form.value = {
    id: "",
    planName: "",
    planType: 1, // 默认总体预案
    eventCategory: 1, // 默认自然灾害
    eventLevel: 5, // 默认全部
    publishUnit: "",
    publishDate: dayjs().format("YYYY-MM-DD"),
    effectiveDate: dayjs().format("YYYY-MM-DD"),
    planStatus: 1, // 默认启用
    attachmentPath: "",
    notifyPersonnel: [], // 通知人员
    noticeRecords: [] // 存储通知记录
  };
  fileList.value = [];
  // 获取部门数据
  await getDeptTreeData();
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row) => {
  try {
    dialogTitle.value = "编辑应急预案";
    dialogVisible.value = true;
    
    // 获取部门数据
    await getDeptTreeData();
    
    const res = await getEmergencyPlanById(row.id);
    if (res.code === 200) {
      form.value = {
        ...res.data,
        publishDate: res.data.publishDate ? dayjs(res.data.publishDate).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD'),
        effectiveDate: res.data.effectiveDate ? dayjs(res.data.effectiveDate).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD'),
        notifyPersonnel: [], // 初始化为空，等待从通知记录中加载
        noticeRecords: [] // 初始化为空，等待从API加载
      };
      
      // 设置文件列表
      fileList.value = [];
      if (form.value.attachmentPath) {
        fileList.value = [{
          name: form.value.attachmentPath.split('/').pop() || '附件',
          url: form.value.attachmentPath
        }];
      }
      
      // 获取该预案的通知记录
      await getPlanNoticeRecords(row.id);
    }
  } catch (error) {
    ElMessage.error("获取详情失败");
  }
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该应急预案吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      const res = await deleteEmergencyPlan(row.id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

// 表格选择改变
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 移除notifyPersonnel和noticeRecords字段，后端API不需要
        const { notifyPersonnel, noticeRecords, ...submitData } = { ...form.value };
        console.log('提交的预案数据:', submitData);
        
        let planId = form.value.id;
        console.log('预案ID:', planId);
        let isCreate = !planId;

        // 提交预案数据
        if (isCreate) {
          // 新增预案
          const res = await addEmergencyPlan(submitData);
          if (res.code === 200) {
            planId = res.data;
            console.log('新增预案成功，获取到的预案ID:', planId);
            ElMessage.success("新增预案成功");
          } else {
            ElMessage.error(res.msg || "新增预案失败");
            return;
          }
        } else {
          // 修改预案
          const res = await updateEmergencyPlan(submitData);
          if (res.code === 200) {
            console.log('修改预案成功');
            ElMessage.success("修改预案成功");
          } else {
            ElMessage.error(res.msg || "修改预案失败");
            return;
          }
        }

        // 处理通知人员数据
        console.log('开始处理通知人员数据');
        
        // 先删除原有关联关系(如果是编辑)
        if (!isCreate && form.value.noticeRecords && form.value.noticeRecords.length > 0) {
          console.log('删除原有通知记录:', form.value.noticeRecords);
          
          try {
            // 这里可以根据实际需求决定是批量删除还是逐个删除
            const deletePromises = form.value.noticeRecords.map(record => 
              record.id ? deletePlanNoticeRecord(record.id) : Promise.resolve()
            );
            await Promise.all(deletePromises);
            console.log('原有通知记录删除成功');
          } catch (deleteError) {
            console.error('删除原有通知记录失败:', deleteError);
            ElMessage.warning('部分通知人员记录可能未能完全清除');
            // 继续执行，尝试添加新记录
          }
        }

        // 添加新的通知人员关联
        if (form.value.notifyPersonnel && form.value.notifyPersonnel.length > 0) {
          console.log('准备添加新的通知记录，选中的用户/部门:', form.value.notifyPersonnel);
          
          // 获取所有选中的部门节点
          const checkedDeptNodes = deptTreeRef.value ? deptTreeRef.value.getCheckedNodes() : [];
          const halfCheckedDeptNodes = deptTreeRef.value ? deptTreeRef.value.getHalfCheckedNodes() : [];
          const allCheckedDepts = [...checkedDeptNodes, ...halfCheckedDeptNodes];
          
          // 创建部门ID映射，方便查找
          const deptMap = {};
          const collectDepts = (nodes) => {
            nodes.forEach(node => {
              deptMap[node.deptId] = node;
              if (node.children && node.children.length > 0) {
                collectDepts(node.children);
              }
            });
          };
          collectDepts(deptOptions.value);
          
          // 构建通知记录数据
          const noticeRecords = [];
          
          // 首先处理用户选择(带有 deptId-userId 格式的记录)
          form.value.notifyPersonnel.forEach(userKey => {
            if (userKey.includes('-')) {
              const [deptId, userId] = userKey.split('-');
              // 从部门树中查找用户信息
              const userInfo = findUserInfo(deptId, userId);
              if (userInfo) {
                noticeRecords.push({
                  planId: planId,
                  departmentId: deptId,
                  departmentName: userInfo.deptName,
                  personnelId: userId,
                  personnelName: userInfo.nickName || userInfo.userName
                });
              }
            }
          });
          
          // 然后处理部门选择(所有选中的部门，不带用户ID)
          allCheckedDepts.forEach(dept => {
            const deptId = String(dept.deptId);
            // 检查该部门是否已经有用户级别的记录
            const hasDeptUserRecord = noticeRecords.some(record => 
              String(record.departmentId) === deptId && record.personnelId
            );
            
            // 如果没有用户级别的记录，则添加部门级别的记录
            if (!hasDeptUserRecord) {
              noticeRecords.push({
                planId: planId,
                departmentId: deptId,
                departmentName: dept.deptName,
                personnelId: null,  // 无用户ID
                personnelName: null  // 无用户名
              });
            }
          });
          
          console.log('准备添加的通知记录:', noticeRecords);

          try {
            // 将通知记录打包成一个数组并发送给后端
            const res = await addPlanNoticeRecord(noticeRecords);
            if (res.code === 200) {
              console.log('添加通知记录成功');
            } else {
              console.error('添加通知记录失败:', res.msg);
              ElMessage.warning('部分通知人员可能未能添加成功');
            }
          } catch (addError) {
            console.error('添加通知记录失败:', addError);
            ElMessage.warning('部分通知人员可能未能添加成功');
          }
        } else {
          console.log('没有选择通知人员，跳过添加通知记录');
        }

        ElMessage.success('预案' + (isCreate ? '新增' : '修改') + '成功');
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("提交表单失败:", error);
        ElMessage.error("操作失败: " + (error.message || '未知错误'));
      }
    } else {
      console.warn('表单验证失败');
    }
  });
};

// 根据部门ID和用户ID查找用户信息
const findUserInfo = (deptId, userId) => {
  const findInDept = (depts) => {
    for (const dept of depts) {
      if (String(dept.deptId) === String(deptId)) {
        const user = dept.users?.find(u => String(u.userId) === String(userId));
        if (user) return user;
      }
      if (dept.children) {
        const found = findInDept(dept.children);
        if (found) return found;
      }
    }
    return null;
  };
  
  return findInDept(deptOptions.value);
};

// 上传文件前的钩子
const beforeUpload = (file) => {
  // 这里可以添加文件类型、大小等限制
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.error('上传文件大小不能超过 5MB!');
    return false;
  }
  return true;
};

// 文件上传成功回调
const handleUploadSuccess = (response, file) => {
  if (response.code === 200) {
    form.value.attachmentPath = response.data.url;
    ElMessage.success('上传成功');
  } else {
    ElMessage.error(response.msg || '上传失败');
  }
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

// 获取事件类型名称
const getEventCategoryName = (category) => {
  const categories = {
    1: '自然灾害',
    2: '事故灾难',
    3: '公共卫生事件',
    4: '社会安全事件'
  };
  return categories[category] || '-';
};

// 获取事件类型标签类型
const getEventCategoryTag = (category) => {
  const tagTypes = {
    1: 'warning',
    2: 'danger',
    3: 'info',
    4: 'success'
  };
  return tagTypes[category] || '';
};

// 获取事件等级名称
const getEventLevelName = (level) => {
  const levels = {
    1: 'Ⅰ级',
    2: 'Ⅱ级',
    3: 'Ⅲ级',
    4: 'Ⅳ级',
    5: '全部'
  };
  return levels[level] || '-';
};

// 获取事件等级标签类型
const getEventLevelTag = (level) => {
  const tagTypes = {
    1: 'danger',    // Ⅰ级 - 最严重，显示红色
    2: 'warning',   // Ⅱ级 - 较严重，显示橙色
    3: 'primary',   // Ⅲ级 - 一般严重，显示蓝色
    4: 'info',      // Ⅳ级 - 较轻，显示灰色
    5: 'success'    // 全部 - 最轻，显示绿色
  };
  return tagTypes[level] || '';
};

// 获取预案状态名称
const getPlanStatusName = (status) => {
  const statuses = {
    1: '启用',
    2: '停用',
    3: '修订中'
  };
  return statuses[status] || '-';
};

// 获取预案状态标签类型
const getPlanStatusTag = (status) => {
  const tagTypes = {
    1: 'success',  // 启用 - 显示绿色
    2: 'danger',   // 停用 - 显示红色
    3: 'warning'   // 修订中 - 显示橙色
  };
  return tagTypes[status] || '';
};

// 文件上传相关
const uploadDialogVisible = ref(false);
const uploadRef = ref();
const uploadFiles = ref([]);
const currentRow = ref(null);
const uploading = ref(false);
const uploadProgress = ref({
  current: 0,
  total: 0,
  status: 'primary'
});

// 处理文件选择
const handleFileChange = (file, fileList) => {
  uploadFiles.value = fileList;
};

// 处理文件移除
const handleFileRemove = (file, fileList) => {
  uploadFiles.value = fileList;
};

// 处理超出文件数限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传10个文件');
};

// 格式化进度条文字
const progressFormat = (percentage) => {
  return `${uploadProgress.value.current}/${uploadProgress.value.total}`;
};

// 处理附件查看
const handleViewAttachment = (row) => {
  if (row.ossList && row.ossList.length > 0) {
    attachmentList.value = row.ossList;
    attachmentDialogVisible.value = true;
  } else {
    ElMessage.warning('暂无附件');
  }
};

// 处理附件上传点击
const handleUploadAttachment = (row) => {
  currentRow.value = row;
  uploadDialogVisible.value = true;
  uploadFiles.value = [];
  uploadProgress.value = {
    current: 0,
    total: 0,
    status: 'primary'
  };
};

// 提交文件上传
const submitUpload = async () => {
  if (!uploadFiles.value.length) {
    ElMessage.warning('请先选择要上传的文件');
    return;
  }

  uploading.value = true;
  uploadProgress.value.total = uploadFiles.value.length;
  uploadProgress.value.current = 0;
  uploadProgress.value.status = 'primary';

  try {
    for (const file of uploadFiles.value) {
      const formData = new FormData();
      console.log(file)
      formData.append('file', file.raw);
      formData.append('id', currentRow.value.id);
      console.log(formData)
      await uploadEmergencyPlanAttachment(formData);
      uploadProgress.value.current++;
    }

    uploadProgress.value.status = 'success';
    ElMessage.success('文件上传成功');
    await getList(); // 刷新列表
    setTimeout(() => {
      uploadDialogVisible.value = false;
      uploading.value = false;
      uploadFiles.value = [];
    }, 1000);
  } catch (error) {
    uploadProgress.value.status = 'exception';
    ElMessage.error('文件上传失败');
    uploading.value = false;
  }
};

// 删除附件
const handleDeleteAttachment = (file) => {
  ElMessageBox.confirm(
    `确定要删除文件 "${file.fileName}" 吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 假设这是删除附件的API调用
      const res = await deleteEmergencyPlanAttachment(file.ossId);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        // 重新获取附件列表或从当前列表中移除
        attachmentList.value = attachmentList.value.filter(item => item.ossId !== file.ossId);
      }
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 取消删除操作
  });
};

// 处理文件下载
const handleDownload = (file) => {
  console.log(file)
    if (file.url) {
        // 发起请求获取文件
        fetch(file.url)
           .then(response => response.blob())
           .then(blob => {
                // 创建一个 URL 对象
                const url = window.URL.createObjectURL(blob);
                // 创建一个 a 标签
                const a = document.createElement('a');
                // 设置 a 标签的 href 属性为文件的 URL
                a.href = url;
                // 设置下载的文件名
                a.download = file.fileName || '文件';
                // 模拟点击 a 标签进行下载
                a.click();
                // 释放 URL 对象
                window.URL.revokeObjectURL(url);
            })
           .catch(error => {
                console.error('下载文件时出错:', error);
                ElMessage.error('下载链接无效');
            });
    } else {
        ElMessage.error('下载链接无效');
    }
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.planName = null;
  queryParams.planType = null;
  handleQuery();
};

onMounted(() => {
  getList(); // 获取应急预案列表
  getDeptTreeData(); // 获取部门树状数据
});
</script>

<style scoped lang="scss">
$bg-color-page: var(--el-bg-color-page);
$bg-color-overlay: var(--el-bg-color-overlay);
$box-shadow-light: var(--el-box-shadow-light);
$box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
$border-radius: 4px;
$border-radius-dialog: 8px;
$border-color-light: var(--el-border-color-light);
$color-primary: var(--el-color-primary);
$primary-color: #409eff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$deep-box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
$header-padding: 15px 20px;
$general-padding: 20px;
$footer-padding: 10px 20px;
$divider-color: #f0f0f0;

.list-page {
  padding: 20px;
  background: $bg-color-page;
  border-radius: $border-radius;
  box-shadow: $box-shadow-light;
  display: flex;
  gap: 20px;
}

.content-container {
  flex: 1;
  overflow: hidden;
}

.filter-area {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  background: $bg-color-overlay;
  padding: 16px;
  border-radius: $border-radius;
}

.search-input {
  width: 300px;
  margin-left: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
  background: $bg-color-overlay;

  :deep(th) {
    background: $bg-color-page !important;
  }
}

/* 状态标签特殊样式 */
.status-tag {
  font-weight: bold;
  
  &.status-1 {
    background: var(--el-color-success-light-8) !important;
    color: var(--el-color-success-dark-2) !important;
    border-color: var(--el-color-success) !important;
  }
  
  &.status-2 {
    background: var(--el-color-danger-light-8) !important;
    color: var(--el-color-danger-dark-2) !important;
    border-color: var(--el-color-danger) !important;
  }
  
  &.status-3 {
    background: var(--el-color-warning-light-8) !important;
    color: var(--el-color-warning-dark-2) !important;
    border-color: var(--el-color-warning) !important;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: $bg-color-page;
  border-radius: $border-radius-dialog $border-radius-dialog 0 0;
  border-bottom: 1px solid $border-color-light;

  .dialog-title {
    font-size: 18px;
    color: #303133;
    font-weight: 600;
  }

  .action-buttons {
    display: flex;
    gap: 12px;
  }
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: $border-radius-dialog;
    box-shadow: $box-shadow;

    .el-dialog__body {
      padding: 24px;
      background: $bg-color-overlay;
    }

    .el-dialog__header {
      padding: 0;
      margin: 0;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #303133;
        font-size: 24px;
        z-index: 1000;

        &:hover {
          color: $color-primary;
        }
      }
    }

    .el-dialog__footer {
      padding: 10px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }
}
</style>
